﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using qltscd.Models;
using qltscd.Models.ScreenClient;
using qltscd.Contansts;
using Telerik.Web.Mvc;
using qltscd.Helper;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.IO;
using System.Text;
using System.Web.Routing;

namespace qltscd.Controllers
{
    public class DanhMucNhaCungCapController : BaseController
    {
        protected override void OnActionExecuting (ActionExecutingContext filterContext) {
            base.OnActionExecuting(filterContext);
            if (SessionHelper.QuyenNhom[qltscd.Contansts.KeyContansts.QuyenDanhMuc] == '0') {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
                    controller = "KhongCoQuyen",
                    action = "Index"
                }));
            }
        }
        #region Properties Section
        private QLTBEntities db = new QLTBEntities();
        #endregion

        #region Views Section
        public ViewResult Index()
        {
            DMNCCScreenClient screen = new DMNCCScreenClient();
            if (Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT] != null) {
                screen = (DMNCCScreenClient)Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT];
            }
            Search(screen);
            return View(screen);
        }
        [HttpPost]
        public ActionResult Index (DMNCCScreenClient screen) {
            Search(screen);
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index () {
            DMNCCScreenClient screen = new DMNCCScreenClient();
            if (Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT] != null) {
                screen = (DMNCCScreenClient)Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT];
            }
            Search(screen);
            return View(new GridModel(screen.DSNhaCungCap));
        }
        public ActionResult Create()
        {
            Models.BaseClient.DanhMucNhaCungCap ncc = new Models.BaseClient.DanhMucNhaCungCap() { IdentityNhaCungCap = -1 };
            return View(ncc);
        }

        public ActionResult SuaNhaCungCap()
        {
            string id = Request.QueryString["id"];
            if (id != null)
            {
                int iden = Convert.ToInt32(id);
                DanhMucNhaCungCap ncc = db.DanhMucNhaCungCaps.Single(i => i.IdentityNhaCungCap == iden);
                Models.BaseClient.DanhMucNhaCungCap nccC = new Models.BaseClient.DanhMucNhaCungCap();
                ObjectHelper.Copy(ncc, nccC);
                return View(nccC);

            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult ShowPdf()
        {
            ReportClass rpt = new ReportClass();
            rpt.FileName = Server.MapPath("~/") + "//Reports//rDanhMucNhaCungCap.rpt";
            rpt.Load();
            rpt.SetDatabaseLogon("sa", "sa");
            //rpt.SetDataSource(db.DanhMucNhaCungCaps);
            Stream stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return File(stream, "application/pdf");
        }

        public FileResult ExportToExcel()
        {

            DataTable myTable = new DataTable();

            var data = from n in db.DanhMucNhaCungCaps
                       select n;

            myTable.Columns.Add("Mã Nhà Cung Cấp");
            myTable.Columns.Add("Tên Nhà Cung Cấp");
            myTable.Columns.Add("Mã Số Thuế");
            myTable.Columns.Add("Địa Chỉ");
            myTable.Columns.Add("Điện Thoại");
            myTable.Columns.Add("Trang Web");
            myTable.Columns.Add("Người Bảo Hành");
            myTable.Columns.Add("Địa Chỉ Bảo Hành");
            myTable.Columns.Add("Điện Thoại Bào Hành");

            foreach (var n in data)
            {
                myTable.Rows.Add(n.MaNhaCungCap.ToString(), n.TenNhaCungCap.ToString(), n.MaSoThue, n.DiaChi, n.DienThoai, n.TrangWeb, n.NguoiBaoHanh, n.DiaChiBaoHanh, n.DienThoaiBaoHanh);
            }

            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + "BaoCaoDanhMucNhaCungCap.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("DANH MỤC NHÀ CUNG CẤP\t\t\t\n\n");
                for (int count = 0; count < myTable.Columns.Count; count++)
                {
                    if (myTable.Columns[count].ColumnName != null)
                        sb.Append(myTable.Columns[count].ColumnName);
                    if (count < myTable.Columns.Count - 1)
                        sb.Append("\t");
                }

                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                int soDem = 0;
                while (myTable.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();
                    for (int col = 0; col < myTable.Columns.Count - 1; col++)
                    {
                        if (myTable.Rows[soDem][col] != null)
                            sb.Append(myTable.Rows[soDem][col].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    if (myTable.Rows[soDem][myTable.Columns.Count - 1] != null)
                        sb.Append(myTable.Rows[soDem][myTable.Columns.Count - 1].ToString().Replace(",", " "));
                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch
            {

            }

            myTable.Dispose();
            Response.End();
            return File("BaoCaoDanhMucNhaCungCap", "application/ms-excel", "BaoCaoDanhMucNhaCungCap.xls");
        }
        #endregion

        #region CRUD Section
        [HttpPost]
        public ActionResult SuaNhaCungCap(Models.BaseClient.DanhMucNhaCungCap nccC)
        {
            if (ModelState.IsValid)
            {
                //code de luu lai
                DanhMucNhaCungCap n = db.DanhMucNhaCungCaps.Single(i => i.IdentityNhaCungCap == nccC.IdentityNhaCungCap);
                if (n.MaNhaCungCap != nccC.MaNhaCungCap) {
                    if (db.DanhMucNhaCungCaps.Count(o => o.MaNhaCungCap == n.MaNhaCungCap) > 0) {
                        ViewData[SessionConstants.ERROR_MESSAGE] = "Mã nhà cung cấp " + nccC.MaNhaCungCap + " đã tồn tại";
                        return View(nccC);
                    }
                }
                ObjectHelper.Copy(nccC, n);
                db.ObjectStateManager.ChangeObjectState(n, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(nccC);
        }

        [HttpPost]
        public ActionResult Create(Models.BaseClient.DanhMucNhaCungCap danhmucnhacungcap)
        {
            if (ModelState.IsValid)
            {
                DanhMucNhaCungCap ncc = new DanhMucNhaCungCap();
                if (danhmucnhacungcap.IdentityNhaCungCap == -1)
                {
                    //danhmucnhacungcap.MaNhaCungCap = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                    if (danhmucnhacungcap.MaNhaCungCap != ncc.MaNhaCungCap)
                    {
                        if (db.DanhMucNhaCungCaps.Count(o => o.MaNhaCungCap == danhmucnhacungcap.MaNhaCungCap) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã nhà cung cấp " + danhmucnhacungcap.MaNhaCungCap + " đã tồn tại";
                            return View(danhmucnhacungcap);
                        }
                    }
                    ObjectHelper.Copy(danhmucnhacungcap, ncc);
                    db.DanhMucNhaCungCaps.AddObject(ncc);
                }
                else
                {
                    ncc = db.DanhMucNhaCungCaps.Single(i => i.IdentityNhaCungCap == danhmucnhacungcap.IdentityNhaCungCap);//lấy 1 thằng
                    if (danhmucnhacungcap.MaNhaCungCap != ncc.MaNhaCungCap)
                    {
                        if (db.DanhMucNhaCungCaps.Count(o => o.MaNhaCungCap == danhmucnhacungcap.MaNhaCungCap) > 0)
                        {
                            ViewData[SessionConstants.ERROR_MESSAGE] = "Mã nhà cung cấp " + danhmucnhacungcap.MaNhaCungCap + " đã tồn tại";
                            return View(danhmucnhacungcap);
                        }
                    }
                    ObjectHelper.Copy(danhmucnhacungcap, ncc);
                    db.ObjectStateManager.ChangeObjectState(ncc, EntityState.Modified);
                }
                db.SaveChanges();
                return RedirectToAction("Create");
            }
            return View(danhmucnhacungcap);
        }

        public ActionResult Delete(int id)
        {
            DanhMucNhaCungCap ncc = db.DanhMucNhaCungCaps.Single(i => i.IdentityNhaCungCap == id);
            db.DanhMucNhaCungCaps.DeleteObject(ncc);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult XoaNhaCungCap()
        {
            string id = Request.QueryString["id"];
            try
            {
                if (id != null)
                {
                    int iden = Convert.ToInt32(id);
                    DanhMucNhaCungCap ncc = db.DanhMucNhaCungCaps.Single(i => i.IdentityNhaCungCap == iden);
                    db.DanhMucNhaCungCaps.DeleteObject(ncc);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        
        #endregion

        #region Helper Section
        private void Search (DMNCCScreenClient screen) {
            if (Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT] != null) {
                screen = (DMNCCScreenClient)Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT];
            } else {
                screen = new DMNCCScreenClient();
            }
            screen.DSNhaCungCap.Clear();
            var list = db.DanhMucNhaCungCaps.OrderBy(i => i.TenNhaCungCap).ToList();
            foreach (DanhMucNhaCungCap DMNCC in list) {
                qltscd.Models.BaseClient.DanhMucNhaCungCap DMNCCClient = new Models.BaseClient.DanhMucNhaCungCap();
                ObjectHelper.Copy(DMNCC, DMNCCClient);
                screen.DSNhaCungCap.Add(DMNCCClient);
            }
            Session[SessionScreenContansts.DanhMucNhaCungCap_SCREENCLIENT] = screen;
        }
        #endregion

        #region Additional Section
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        #endregion
    }
}
